package com.example.lottery.service.activitystatus.operator;

import com.example.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.example.lottery.common.exception.ServiceException;
import com.example.lottery.dao.dataobject.ActivityUserDO;
import com.example.lottery.dao.mapper.ActivityUserMapper;
import com.example.lottery.service.dto.ConvertActivityStatusDTO;
import com.example.lottery.service.enums.ActivityUserEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class UserOperator extends AbstractOperator{
    @Autowired
    private ActivityUserMapper activityUserMapper;
    @Override
    public Integer sequence() {
        return 1;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        //1-    校验参数，目标状态是否为空 是否为COMPLETE
        if(convertActivityStatusDTO==null||
                convertActivityStatusDTO.getTargetActivityStatus()==null
        ||!convertActivityStatusDTO.getTargetActivityStatus().name().equalsIgnoreCase(ActivityUserEnum.COMPLETE.name())){
            log.warn("参数、目标状态错误");
            return false;
        }
        //2-    判断判断用户、活动是否为空 后期进行扭转时会用到
        Long activityId = convertActivityStatusDTO.getActivityId();
        List<Long> userIds = convertActivityStatusDTO.getUserIds();
        if(activityId==null||userIds.isEmpty()){
            log.warn("用户列表、活动为空");
            return false;
        }
        try {
            //3-    判断活动用户表中是否存在记录
            List<Long>userIdsData = activityUserMapper.selectUAId(userIds,activityId);
            for (Long userId : userIds) {
                if (!userIdsData.contains(userId)) {
                    log.warn("活动用户表中不存在 userId:{} activityId:{}", userId, activityId);
                    return false;
                }
            }
        }catch (Exception e){
            //sql异常
            log.warn("sql查询活动用户表记录异常");
            return false;
        }
        return true;
    }

    @Override
    public Boolean convertStatus(ConvertActivityStatusDTO convertActivityStatusDTO) {
        //1-    获取用户Id
        List<Long> userIds = convertActivityStatusDTO.getUserIds();
        //2-    将userIds的每一个状态修改
        try{
            int i = activityUserMapper.updateStatus(userIds,
                    convertActivityStatusDTO.getTargetUserStatus().name(),
                    convertActivityStatusDTO.getActivityId());
            if(i==0){
                log.warn("逆转活动用户表状态失败");
                return false;
            }
        }catch (Exception e){
            log.warn("sql逆转活动用户表状态异常");
            return false;
        }
        return true;
    }
}
